//
//  HomeViewController.m
//  MyLittleBrother
//
//  Created by speeda on 17/7/17.
//  Copyright © 2017年 speeda. All rights reserved.
//

#import "HomeViewController.h"
#import "HomeCell.h"
#import "PersonalViewController.h"
#import "RegisterViewController.h"
#import "LoginViewController.h"
#import "TalkViewController.h"
#import "StrangeThingViewController.h"
#import "NewsViewController.h"
#import "OtherInfoViewController.h"
#import "DetailsViewController.h"
#import "ArticleModel.h"
#import <TZPhotoPreviewController.h>
#import "ACMediaFrame.h"
#import "TaskView.h"
#import "CoverView.h"

@interface HomeViewController () <UITableViewDataSource,UITableViewDelegate,HomeCellDelegate>

@property (weak, nonatomic) IBOutlet UITableView *articleTableView;
@property (nonatomic, strong) NSMutableArray *articleArray;
@property (weak, nonatomic) IBOutlet UIView *headView;

@property (nonatomic, assign) NSInteger page;


@end

@implementation HomeViewController

- (void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setNavigationItem];
    
    [self initTableView];
    
}


- (void)initTableView {
    
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleCustom];
    [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
    [SVProgressHUD setBackgroundColor:[UIColor grayColor]];
    [SVProgressHUD setMinimumDismissTimeInterval:0.5];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeGradient];
    
    self.articleTableView.estimatedRowHeight = 100;
    self.articleTableView.rowHeight = UITableViewAutomaticDimension;
    self.articleTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.articleTableView.tableFooterView = [[UIView alloc] init];
    self.articleTableView.dataSource = self;
    self.articleTableView.delegate = self;
    
    __weak typeof(self) weakSelf = self;
    //默认block方法：设置下拉刷新
    self.articleTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf AFNNewData];
    }];
    [self.articleTableView.mj_header beginRefreshing];
    
    //默认block方法：设置上拉加载更多
    self.articleTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [weakSelf AFNMoreData];
    }];
    
}


- (void)setNavigationItem {

    UIButton *leftBtton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtton.contentEdgeInsets = UIEdgeInsetsMake(20, 0, 0, 0);
    [leftBtton addTarget:self action:@selector(leftItemAction) forControlEvents:UIControlEventTouchUpInside];
    [leftBtton setImage:[UIImage imageNamed:@"logo"] forState:UIControlStateNormal];
    [leftBtton sizeToFit];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtton];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    UIButton *writeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [writeBtn addTarget:self action:@selector(writeBtnItemAction) forControlEvents:UIControlEventTouchUpInside];
    [writeBtn setImage:[UIImage imageNamed:@"btn_write"] forState:UIControlStateNormal];
    [writeBtn sizeToFit];
    UIBarButtonItem *writeBtnItem = [[UIBarButtonItem alloc] initWithCustomView:writeBtn];
    
    
    UIButton *huatiBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [huatiBtn addTarget:self action:@selector(huatiBtnItemAction) forControlEvents:UIControlEventTouchUpInside];
    [huatiBtn setImage:[UIImage imageNamed:@"btn_huati"] forState:UIControlStateNormal];
    [huatiBtn sizeToFit];
    UIBarButtonItem *huatiBtnItem = [[UIBarButtonItem alloc] initWithCustomView:huatiBtn];
    
    UIButton *xiaoxiBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [xiaoxiBtn addTarget:self action:@selector(xiaoxiBtnItemAction) forControlEvents:UIControlEventTouchUpInside];
    [xiaoxiBtn setImage:[UIImage imageNamed:@"btn_xiaoxi"] forState:UIControlStateNormal];
    [xiaoxiBtn sizeToFit];
    UIBarButtonItem *xiaoxiBtnItem = [[UIBarButtonItem alloc] initWithCustomView:xiaoxiBtn];
    
    self.navigationItem.rightBarButtonItems  = @[xiaoxiBtnItem,huatiBtnItem,writeBtnItem];
}


- (void)leftItemAction {
    
    NSString *userid = [[NSUserDefaults standardUserDefaults] objectForKey:kUserid];
    if (userid) {
        
        PersonalViewController *personVc = [[PersonalViewController alloc] init];
        [self.navigationController pushViewController:personVc animated:YES];
        
    } else {
        
        LoginViewController *loginVc = [[LoginViewController alloc] init];
        [self.navigationController pushViewController:loginVc animated:YES];
        
    }
    
}

#pragma mark -- 发新鲜事
- (void)writeBtnItemAction {

    NSString *userid = [[NSUserDefaults standardUserDefaults] objectForKey:kUserid];
    if (userid) {
        
        StrangeThingViewController *strangeThingVc =[[StrangeThingViewController alloc] init];
        strangeThingVc.topicid = nil;
        strangeThingVc.topicString = nil;
        [self.navigationController pushViewController:strangeThingVc animated:YES];
        
    } else {
        
        LoginViewController *loginVc = [[LoginViewController alloc] init];
        [self.navigationController pushViewController:loginVc animated:YES];
        
    }

}


#pragma mark -- 更多话题
- (void)huatiBtnItemAction {
    
    NSString *userid = [[NSUserDefaults standardUserDefaults] objectForKey:kUserid];
    if (userid) {
        
        TalkViewController *talkVc = [[TalkViewController alloc] init];
        [self.navigationController pushViewController:talkVc animated:YES];
        
    } else {
        
        LoginViewController *loginVc = [[LoginViewController alloc] init];
        [self.navigationController pushViewController:loginVc animated:YES];
        
    }
}


#pragma mark -- 消息
- (void)xiaoxiBtnItemAction {
    
    NSString *userid = [[NSUserDefaults standardUserDefaults] objectForKey:kUserid];
    if (userid) {
        
        NewsViewController *newsVc =[[NewsViewController alloc] init];
        [self.navigationController pushViewController:newsVc animated:YES];
        
    } else {
        
        LoginViewController *loginVc = [[LoginViewController alloc] init];
        [self.navigationController pushViewController:loginVc animated:YES];
        
    }
    
}


#pragma mark -- 任务
- (IBAction)taskBtnAction:(id)sender {
    
    TaskView *view = [TaskView viewFormXib];
    view.frame = CGRectMake(SCREEN_WIDTH, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    [CoverView showCoverView];
    [[UIApplication sharedApplication].keyWindow addSubview:view];
    [UIView animateWithDuration:0.4 animations:^{
        
        view.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);

    }];
    
}



#pragma mark -- 获取贴子
- (void)AFNNewData {
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"command"] = @"getarticle";
    dict[@"topicid"] = @"";
    dict[@"circleid"] = @"";
    dict[@"page"] = @"1";
    
    [AFHTTPSTool POSTRequestRequestWebsite:Url AndDictionary:dict success:^(NSURLSessionDataTask *dataTask, id responseObject) {
        
        [self.articleTableView.mj_header endRefreshing];
        
        NSDictionary *dic = responseObject;
        NSString *state = [NSString stringWithFormat:@"%@",dic[@"code"]];
        if ([state isEqualToString:@"000000"]) {
            
            [self.articleArray removeAllObjects];
            
            NSLog(@"获取贴子 = %@",responseObject);
           NSArray *array = [ArticleModel mj_objectArrayWithKeyValuesArray:[dic[@"data"] objectForKey:@"rows"]];
            
            NSString *pageString = [dic[@"data"] objectForKey:@"page"];
            _page = pageString.integerValue;
            _page++;

            [self.articleArray addObjectsFromArray:array];
            
            [self.articleTableView reloadData];
            
        } else {
            
            NSString *errorText = [NSString stringWithFormat:@"%@",dic[@"msg"]];
            [SVProgressHUD showInfoWithStatus:errorText];
        }
        
        
    } failure:^(NSURLSessionDataTask *dataTask, NSError *error) {
        
        [self.articleTableView.mj_header endRefreshing];
        [SVProgressHUD showErrorWithStatus:error.localizedDescription];
    }];
}


- (void)AFNMoreData {
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"command"] = @"getarticle";
    dict[@"topicid"] = @"";
    dict[@"circleid"] = @"";
    dict[@"page"] = @(_page);
    
    [AFHTTPSTool POSTRequestRequestWebsite:Url AndDictionary:dict success:^(NSURLSessionDataTask *dataTask, id responseObject) {
        
        [self.articleTableView.mj_footer endRefreshing];
        
        NSDictionary *dic = responseObject;
        NSString *state = [NSString stringWithFormat:@"%@",dic[@"code"]];
        if ([state isEqualToString:@"000000"]) {
                        
            NSLog(@"获取贴子 = %@",responseObject);
            NSArray *array = [ArticleModel mj_objectArrayWithKeyValuesArray:[dic[@"data"] objectForKey:@"rows"]];
            
            NSString *pageString = [dic[@"data"] objectForKey:@"page"];
            _page = pageString.integerValue;
            _page++;
            
            [self.articleArray addObjectsFromArray:array];
            
            [self.articleTableView reloadData];
            
        } else {
            
            NSString *errorText = [NSString stringWithFormat:@"%@",dic[@"msg"]];
            [SVProgressHUD showInfoWithStatus:errorText];
        }
        
        
    } failure:^(NSURLSessionDataTask *dataTask, NSError *error) {
        
        [self.articleTableView.mj_footer endRefreshing];
        [SVProgressHUD showErrorWithStatus:error.localizedDescription];
    }];
}



#pragma maek -- UITableViewDataSource,UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.articleArray.count;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *cellID = @"homeCell";
    HomeCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"HomeCell" owner:nil options:nil];
        cell = [nibs firstObject];
    }
    ArticleModel *articleItem = self.articleArray[indexPath.row];
    cell.articleItem = articleItem;
    cell.delegate = self;
    
    return cell;
}




- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    ArticleModel *articleItem = self.articleArray[indexPath.row];
    DetailsViewController *detailsVc = [[DetailsViewController alloc] init];
    detailsVc.circleid = articleItem.b_id;
    [self.navigationController pushViewController:detailsVc animated:YES];
}




#pragma mark -- HomeCellDelegate
- (void)homeCellDelegateWithButton:(UIButton *)button {
    
    HomeCell *cell = (HomeCell *)button.superview.superview;
    NSIndexPath *indexPath = [self.articleTableView indexPathForCell:cell];
    ArticleModel *articleItem = self.articleArray[indexPath.row];
    OtherInfoViewController *otherVc = [[OtherInfoViewController alloc] init];
    otherVc.b_userid = articleItem.b_userid;
    [self.navigationController pushViewController:otherVc animated:YES];
}





- (NSMutableArray *)articleArray {

    if (!_articleArray) {
        _articleArray = [NSMutableArray array];
    }
    
    return _articleArray;
}




@end
